package com.cm.log_process.log_common.util;

import com.cm.log_process.log_common.entity.Log;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Creator:郭兆鹏
 * Date:2019/12/16
 * 思路：Info日志解析工具类
 */
public class InfoUtil {

    private Properties prop;

    {
        try {
            prop = PropertiesLoaderUtils.loadAllProperties("common.properties");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public List<Log> getLogs() throws IOException {
        List<Log> logs = new ArrayList<>();
        FileReader fileReader = new FileReader(new File(prop.getProperty("basePath")));
        BufferedReader br = new BufferedReader(fileReader);
        String line = null;
        while ((line=br.readLine())!=null){
            if (StringUtils.isEmpty(line)) {
                break;
            }
            if(line.startsWith("INFO")||line.startsWith("WARN")||line.startsWith("#logback")){
                line += readLog(br);
            }else{
                line += readLog(br);
            }
        }
        return logs;
    }

    private List<Log> analyis(String line) {
        List<Log> logs = new ArrayList<>();
        Log log = new Log();
        String matchstr = "(#Serial:)[0-9a-zA-Z]{38,40}";
        //2019-11-25 09:08:59.590
        String matchTime = "(20)([\\d]{2})\\-([1-12]{2})\\-([1-30]{2})\\s([0-24]{2}\\:[0-59]{2}\\:[0-59]{2}\\.[0-999]{3})";
        if(line.startsWith("INFO")||line.startsWith("WARN")||line.startsWith("#logback")){
            Pattern transp = Pattern.compile(matchstr);
            Matcher transm = transp.matcher(line);
            if(transm.find()){
                log.setTransId(transm.group(0));
            }
            Pattern timep = Pattern.compile(matchTime);
            Matcher timem = timep.matcher(line);
            if(timem.find()){
                log.setTimestamp(timem.group(0));
            }
        }else{
           log.setTransId("");
        }

        return logs;

    }

    private String readLog(BufferedReader br) throws IOException {
        String line = br.readLine();
        if(line.startsWith("INFO")||line.startsWith("WARN")){
            return line;
        }else{
            return line+readLog(br);
        }
    }
}
